<template>
  <div class="user-profile">
    <div v-if="loading" class="loading-container">
      <el-spinner size="large" />
    </div>
    
    <template v-else-if="user">
      <!-- 用户信息头部 -->
      <div class="profile-header">
        <div class="profile-banner">
          <img :src="user.banner || 'https://picsum.photos/1200/300'" :alt="用户封面" class="banner-image" />
          <div v-if="isCurrentUser" class="edit-banner-btn">
            <el-button type="primary" size="small" @click="handleBannerUpload">更换封面</el-button>
            <input type="file" ref="bannerInput" accept="image/*" style="display: none;" @change="onBannerUpload" />
          </div>
        </div>
        <div class="profile-info">
          <img :src="user.avatar" :alt="用户头像" class="avatar" />
          <div v-if="isCurrentUser" class="edit-avatar-btn">
            <el-button type="primary" size="small" @click="handleAvatarUpload">更换头像</el-button>
            <input type="file" ref="avatarInput" accept="image/*" style="display: none;" @change="onAvatarUpload" />
          </div>
          <div class="user-details">
            <h1 class="username">{{ user.username }}</h1>
            <p class="user-id">UID: {{ user.id }}</p>
            
            <!-- 用户兴趣标签展示 -->
            <div v-if="user.interests && user.interests.length > 0" class="user-interests">
              <span class="interest-label">兴趣:</span>
              <span 
                v-for="interest in user.interests" 
                :key="interest"
                class="interest-tag"
                @click="searchByInterest(interest)"
              >
                {{ interest }}
              </span>
            </div>
            
            <p class="bio">{{ user.bio || '这个人很懒，什么都没有留下~' }}</p>
            
            <!-- 用户等级 -->
            <div class="user-level">
              <span class="level-badge">Lv.{{ userLevel }}</span>
              <div class="level-progress">
                <div 
                  class="level-progress-bar" 
                  :style="{ width: levelProgress + '%' }"
                ></div>
              </div>
              <span class="level-text">{{ user.experience || 0 }}/1000 经验</span>
            </div>
            
            <div class="user-stats">
              <div class="stat-item">
                <span class="stat-number">{{ user.followers }}</span>
                <span class="stat-label">粉丝</span>
              </div>
              <div class="stat-item">
                <span class="stat-number">{{ user.following }}</span>
                <span class="stat-label">关注</span>
              </div>
              <div class="stat-item">
                <span class="stat-number">{{ user.videos }}</span>
                <span class="stat-label">视频</span>
              </div>
              <div class="stat-item">
                <span class="stat-number">{{ formatViewCount(user.totalViews) }}</span>
                <span class="stat-label">总播放量</span>
              </div>
            </div>
            <div class="action-buttons">
              <button
                v-if="!isCurrentUser"
                :class="['follow-button', { following: isFollowing }]"
                @click="toggleFollow"
              >
                {{ isFollowing ? '已关注' : '关注' }}
              </button>
              <button v-if="!isCurrentUser" class="message-button">私信</button>
              <router-link v-if="isCurrentUser" to="/profile/edit" class="edit-profile-button">
                编辑资料
              </router-link>
            </div>
          </div>
        </div>
      </div>
      <!-- 标签页导航 -->
      <div class="profile-tabs">
        <div 
          v-for="tab in tabs" 
          :key="tab.key"
          :class="['tab-item', { active: activeTab === tab.key }]"
          @click="activeTab = tab.key"
        >
          {{ tab.label }}
        </div>
      </div>
      <!-- 内容区域 -->
      <div class="profile-content">
        <!-- 视频内容 -->
        <div v-if="activeTab === 'videos'" class="videos-container">
          <!-- 内容筛选 -->
          <div v-if="isCurrentUser" class="content-filters">
            <el-select v-model="videoFilter" placeholder="筛选视频" size="small" class="filter-select">
              <el-option label="最新发布" value="latest"></el-option>
              <el-option label="最多播放" value="mostViewed"></el-option>
              <el-option label="最多点赞" value="mostLiked"></el-option>
            </el-select>
          </div>
          <div class="video-grid">
            <div 
              v-for="video in filteredVideos" 
              :key="video.id" 
              class="video-card"
              @click="goToVideo(video.id)"
            >
              <div class="video-cover">
                <img :src="video.coverUrl" :alt="video.title" />
                <span class="video-duration">{{ formatDuration(video.duration) }}</span>
                <div v-if="video.isHot" class="hot-badge">热门</div>
                <div class="video-stats-overlay">
                  <span class="overlay-view">{{ formatViewCount(video.views) }}</span>
                  <span class="overlay-like">{{ formatViewCount(video.likes) }}</span>
                </div>
              </div>
              <div class="video-info">
                <h3 class="video-title">{{ video.title }}</h3>
                <div class="video-stats">
                  <span class="view-count">{{ formatViewCount(video.views) }}</span>
                  <span class="upload-time">{{ formatTimeAgo(video.uploadTime) }}</span>
                </div>
                <!-- 视频标签 -->
                <div v-if="video.tags && video.tags.length > 0" class="video-tags">
                  <span 
                    v-for="tag in video.tags.slice(0, 3)" 
                    :key="tag"
                    class="video-tag"
                    @click.stop="searchByTag(tag)"
                  >
                    #{{ tag }}
                  </span>
                </div>
              </div>
            </div>
            <div v-if="filteredVideos.length === 0" class="empty-content">
              <el-empty description="暂无视频" />
              <div v-if="isCurrentUser" class="empty-action">
                <el-button type="primary">上传第一个视频</el-button>
              </div>
            </div>
          </div>
          <!-- 加载更多 -->
          <div v-if="hasMoreVideos" class="load-more">
            <el-button @click="loadMoreVideos" type="text">加载更多</el-button>
          </div>
        </div>
        <!-- 收藏内容 -->
        <div v-if="activeTab === 'collections'" class="collections-container">
          <div class="video-grid">
            <div 
              v-for="video in collections" 
              :key="video.id" 
              class="video-card"
              @click="goToVideo(video.id)"
            >
              <div class="video-cover">
                <img :src="video.coverUrl" :alt="video.title" />
                <span class="video-duration">{{ formatDuration(video.duration) }}</span>
                <div class="favorite-mark">★</div>
              </div>
              <div class="video-info">
                <h3 class="video-title">{{ video.title }}</h3>
                <div class="video-stats">
                  <span class="view-count">{{ formatViewCount(video.views) }}</span>
                  <span class="uploader">{{ video.uploader }}</span>
                </div>
              </div>
            </div>
            <div v-if="collections.length === 0" class="empty-content">
              <el-empty description="暂无收藏" />
            </div>
          </div>
        </div>
        <!-- 喜欢内容 -->
        <div v-if="activeTab === 'likes'" class="likes-container">
          <div class="video-grid">
            <div 
              v-for="video in likes" 
              :key="video.id" 
              class="video-card"
              @click="goToVideo(video.id)"
            >
              <div class="video-cover">
                <img :src="video.coverUrl" :alt="video.title" />
                <span class="video-duration">{{ formatDuration(video.duration) }}</span>
                <div class="like-mark">👍</div>
              </div>
              <div class="video-info">
                <h3 class="video-title">{{ video.title }}</h3>
                <div class="video-stats">
                  <span class="view-count">{{ formatViewCount(video.views) }}</span>
                  <span class="uploader">{{ video.uploader }}</span>
                </div>
              </div>
            </div>
            <div v-if="likes.length === 0" class="empty-content">
              <el-empty description="暂无喜欢的视频" />
            </div>
          </div>
        </div>
        <!-- 兴趣偏好设置（仅当前用户可见） -->
        <div v-if="activeTab === 'interests' && isCurrentUser" class="interests-container">
          <div class="interests-header">
            <h3>个性化推荐设置</h3>
            <p class="interests-desc">设置您的兴趣偏好，我们将为您推荐更符合您口味的内容</p>
          </div>
          <UserInterestTags 
            v-model="userInterests"
            :userId="user.id"
            :minSelections="1"
            :maxSelections="10"
            @confirm="handleInterestsConfirm"
            @save="handleInterestsSave"
          />
          <div class="recommendation-preview">
            <h4>根据您的兴趣推荐</h4>
            <div class="video-grid small-grid">
              <div 
                v-for="video in recommendedVideos" 
                :key="video.id"
                class="video-card"
                @click="goToVideo(video.id)"
              >
                <div class="video-cover">
                  <img :src="video.coverUrl" :alt="video.title" />
                  <span class="video-duration">{{ formatDuration(video.duration) }}</span>
                </div>
                <div class="video-info">
                  <h3 class="video-title">{{ video.title }}</h3>
                  <div class="video-stats">
                    <span class="view-count">{{ formatViewCount(video.views) }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- 观看历史（仅当前用户可见） -->
        <div v-if="activeTab === 'history' && isCurrentUser" class="history-container">
          <div class="history-header">
            <h3>观看历史</h3>
            <el-button type="text" @click="clearHistory" size="small">清空历史记录</el-button>
          </div>
          <div v-if="viewingHistory.length === 0" class="empty-content">
            <el-empty description="暂无观看历史" />
          </div>
          <div v-else class="history-list">
            <div 
              v-for="item in viewingHistory" 
              :key="item.id"
              class="history-item"
            >
              <div class="history-thumbnail" @click="goToVideo(item.id)">
                <img :src="item.coverUrl" :alt="item.title" />
                <span class="video-duration">{{ formatDuration(item.duration) }}</span>
                <div class="watch-progress">
                  <div class="progress-bar" :style="{ width: item.watchProgressPercentage + '%' }"></div>
                </div>
              </div>
              <div class="history-info">
                <h3 class="history-title" @click="goToVideo(item.id)">{{ item.title }}</h3>
                <div class="history-meta">
                  <span class="uploader">{{ item.uploader }}</span>
                  <span class="watch-time">观看至 {{ formatDuration(item.watchProgress) }}</span>
                  <span class="view-time">{{ formatTimeAgo(item.viewTime) }}</span>
                </div>
                <div class="history-actions">
                  <button class="action-btn" @click.stop="removeHistoryItem(item.id)">删除</button>
                  <button class="action-btn" @click.stop="addHistoryToCollection(item.id)">收藏</button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </template>
    <div v-else class="error-container">
      <el-empty description="用户不存在" />
      <router-link to="/" class="go-home-btn">返回首页</router-link>
    </div>
  </div>
</template>

<script>
import { authService } from '../services/authService'
import * as videoFunctions from '../services/videoService'
import UserInterestTags from '../components/UserInterestTags.vue'
import { 
  generatePersonalizedRecommendations, 
  updateUserInterests, 
  inferUserInterests 
} from '../services/ageRecommendationService'

export default {
  name: 'UserProfileView',
  components: {
    UserInterestTags
  },
  data() {
    return {
      user: null,
      userVideos: [],
      collections: [],
      likes: [],
      viewingHistory: [],
      recommendedVideos: [],
      userInterests: [],
      activeTab: 'videos',
      videoFilter: 'latest',
      loading: true,
      isFollowing: false,
      hasMoreVideos: false,
      currentPage: 1,
      pageSize: 20,
      tabs: [
        { key: 'videos', label: '投稿视频' },
        { key: 'collections', label: '收藏' },
        { key: 'likes', label: '喜欢' },
        { key: 'interests', label: '兴趣偏好' },
        { key: 'history', label: '观看历史' }
      ]
    }
  },
  computed: {
    isCurrentUser() {
      const currentUser = authService.getCurrentUser()
      return currentUser && currentUser.id === this.$route.params.id
    },
    userLevel() {
      // 简单的等级计算逻辑
      const exp = this.user.experience || 0
      if (exp >= 5000) return 10
      if (exp >= 3000) return 9
      if (exp >= 2000) return 8
      if (exp >= 1500) return 7
      if (exp >= 1000) return 6
      if (exp >= 600) return 5
      if (exp >= 300) return 4
      if (exp >= 150) return 3
      if (exp >= 50) return 2
      return 1
    },
    levelProgress() {
      const exp = this.user.experience || 0
      const levelExp = this.userLevel * 100
      return Math.min(100, (exp % levelExp) / levelExp * 100)
    },
    filteredVideos() {
      let videos = [...this.userVideos]
      
      switch (this.videoFilter) {
        case 'mostViewed':
          videos.sort((a, b) => (b.views || 0) - (a.views || 0))
          break
        case 'mostLiked':
          videos.sort((a, b) => (b.likes || 0) - (a.likes || 0))
          break
        case 'latest':
        default:
          videos.sort((a, b) => new Date(b.uploadTime) - new Date(a.uploadTime))
          break
      }
      
      return videos
    }
  },
  async mounted() {
    await this.fetchUserProfile()
    await this.fetchUserContent()
    if (this.isCurrentUser) {
      this.loadUserInterests()
      this.loadViewingHistory()
    }
  },
  watch: {
    activeTab() {
      this.fetchUserContent()
      if (this.activeTab === 'interests' && this.isCurrentUser) {
        this.loadRecommendedVideos()
      }
    }
  },
  methods: {
    async fetchUserProfile() {
      try {
        const userId = this.$route.params.id
        // 通过服务对象调用方法
          this.user = await authService.getUserProfile(userId)
        
        // 检查是否为当前用户
          const currentUser = authService.getCurrentUser()
        // 暂时保留isFollowing为mock数据
        if (!this.isCurrentUser && currentUser) {
          this.isFollowing = false
        }
      } catch (error) {
        this.$message.error('获取用户信息失败')
      } finally {
        this.loading = false
      }
    },
    
    async fetchUserContent() {
      try {
        const userId = this.$route.params.id
        // 通过服务对象调用方法
        if (this.activeTab === 'videos') {
            this.userVideos = await videoFunctions.getVideosByUserId(userId)
            // 模拟是否有更多视频
            this.hasMoreVideos = this.userVideos.length >= this.pageSize
          } else if (this.activeTab === 'likes') {
            // 使用模拟数据
            const allVideos = await videoFunctions.fetchAllVideos()
            this.likes = allVideos.slice(8, 16)
          } else if (this.activeTab === 'collections') {
            // 使用模拟数据
            const allVideos = await videoFunctions.fetchAllVideos()
            this.collections = allVideos.slice(0, 8)
          }
      } catch (error) {
        console.error('获取用户内容失败', error)
        this.$message.error('获取用户内容失败')
      }
    },
    
    async loadMoreVideos() {
      try {
        this.loading = true
        this.currentPage++
        const userId = this.$route.params.id
        // 模拟加载更多视频
        const moreVideos = await videoFunctions.getVideosByUserId(userId)
        
        this.userVideos = [...this.userVideos, ...moreVideos]
        this.hasMoreVideos = moreVideos.length >= this.pageSize
      } catch (error) {
        console.error('加载更多视频失败:', error)
        this.$message.error('加载更多失败')
      } finally {
        this.loading = false
      }
    },
    
    loadUserInterests() {
      // 加载用户兴趣标签
      if (this.user && this.user.interests) {
        this.userInterests = [...this.user.interests]
      }
    },
    
    loadViewingHistory() {
      // 模拟加载观看历史
      this.viewingHistory = [
        {
          id: '101',
          title: '如何学习Vue3',
          coverUrl: 'https://picsum.photos/300/200?random=1',
          uploader: '技术UP主',
          duration: 600,
          watchProgress: 300,
          watchProgressPercentage: 50,
          viewTime: new Date().getTime() - 3600000
        },
        {
          id: '102',
          title: '美食制作教程',
          coverUrl: 'https://picsum.photos/300/200?random=2',
          uploader: '美食达人',
          duration: 900,
          watchProgress: 900,
          watchProgressPercentage: 100,
          viewTime: new Date().getTime() - 7200000
        }
      ]
    },
    
    async loadRecommendedVideos() {
      try {
        // 使用个性化推荐服务获取推荐视频
        if (this.user && this.user.interests) {
          // 模拟可用内容
          const mockContent = this.userVideos.map(video => ({
            ...video,
            tags: video.tags || [],
            views: video.views || 0,
            likes: video.likes || 0,
            bulletCount: video.bulletCount || 0,
            createdDate: video.uploadTime
          }))
          
          const userData = {
            interests: this.user.interests,
            viewingHistory: this.viewingHistory,
            followedAuthors: this.user.followedAuthors || []
          }
          
          this.recommendedVideos = generatePersonalizedRecommendations(
            userData, 
            mockContent, 
            { limit: 6 }
          )
        }
      } catch (error) {
        console.error('加载推荐视频失败:', error)
      }
    },
    
    handleInterestsConfirm(interests) {
      this.userInterests = interests
      this.handleInterestsSave(interests)
      // 重新加载推荐视频
      this.loadRecommendedVideos()
      
      // 显示成功提示
      this.$message.success('兴趣偏好已更新')
    },
    
    async handleInterestsSave(interests) {
      try {
        // 更新用户兴趣标签
        const success = updateUserInterests(this.user.id, interests)
        if (success) {
          this.user.interests = interests
        }
      } catch (error) {
        console.error('保存兴趣标签失败:', error)
        this.$message.error('保存失败，请重试')
      }
    },
    
    async toggleFollow() {
      try {
        if (this.isFollowing) {
          // 模拟取消关注
          this.isFollowing = false
          this.user.followers--
          this.$message.success('取消关注成功')
        } else {
          // 模拟关注
          this.isFollowing = true
          this.user.followers++
          this.$message.success('关注成功')
        }
      } catch (error) {
        console.error('关注操作失败:', error)
        this.$message.error('操作失败，请重试')
      }
    },
    
    handleBannerUpload() {
      this.$refs.bannerInput.click()
    },
    
    handleAvatarUpload() {
      this.$refs.avatarInput.click()
    },
    
    onBannerUpload(e) {
      const file = e.target.files[0]
      if (file) {
        // 模拟上传成功
        const reader = new FileReader()
        reader.onload = (event) => {
          this.user.banner = event.target.result
          this.$message.success('封面更新成功')
        }
        reader.readAsDataURL(file)
      }
    },
    
    onAvatarUpload(e) {
      const file = e.target.files[0]
      if (file) {
        // 模拟上传成功
        const reader = new FileReader()
        reader.onload = (event) => {
          this.user.avatar = event.target.result
          this.$message.success('头像更新成功')
        }
        reader.readAsDataURL(file)
      }
    },
    
    searchByTag(tag) {
      // 跳转到搜索页面
      this.$router.push(`/search/${encodeURIComponent(tag)}`)
    },
    
    searchByInterest(interest) {
      // 跳转到搜索页面
      this.$router.push(`/search/${encodeURIComponent(interest)}`)
    },
    
    clearHistory() {
      this.$confirm('确定要清空所有观看历史吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.viewingHistory = []
        this.$message.success('历史记录已清空')
      }).catch(() => {
        // 取消操作
      })
    },
    
    removeHistoryItem(id) {
      const index = this.viewingHistory.findIndex(item => item.id === id)
      if (index !== -1) {
        this.viewingHistory.splice(index, 1)
        this.$message.success('记录已删除')
      }
    },
    
    addHistoryToCollection(videoId) {
      // 查找视频
      const video = this.viewingHistory.find(item => item.id === videoId)
      if (video) {
        // 检查是否已收藏
        if (!this.collections.find(item => item.id === videoId)) {
          this.collections.push({
            id: video.id,
            title: video.title,
            coverUrl: video.coverUrl,
            uploader: video.uploader,
            duration: video.duration,
            views: video.views || 0
          })
          this.$message.success('收藏成功')
        } else {
          this.$message.info('已经收藏过了')
        }
      }
    },
    
    goToVideo(videoId) {
      // 记录观看历史
      if (this.isCurrentUser) {
        this.recordViewHistory(videoId)
      }
      this.$router.push(`/video/${videoId}`)
    },
    
    recordViewHistory(videoId) {
      // 实际应用中应该调用API记录观看历史
      const video = this.userVideos.find(v => v.id === videoId)
      if (video) {
        const existingIndex = this.viewingHistory.findIndex(item => item.id === videoId)
        const historyItem = {
          id: video.id,
          title: video.title,
          coverUrl: video.coverUrl,
          uploader: video.uploader || this.user.username,
          duration: video.duration || 0,
          watchProgress: 0,
          watchProgressPercentage: 0,
          viewTime: Date.now()
        }
        
        if (existingIndex !== -1) {
          // 更新已有记录
          this.viewingHistory.splice(existingIndex, 1)
        }
        
        // 添加到历史记录开头
        this.viewingHistory.unshift(historyItem)
        
        // 限制历史记录数量
        if (this.viewingHistory.length > 100) {
          this.viewingHistory = this.viewingHistory.slice(0, 100)
        }
      }
    },
    
    formatViewCount(views) {
      if (views >= 10000) {
        return (views / 10000).toFixed(1) + '万'
      }
      return views
    },
    
    formatDuration(seconds) {
      const minutes = Math.floor(seconds / 60)
      const secs = seconds % 60
      return `${minutes}:${secs.toString().padStart(2, '0')}`
    },
    
    formatTimeAgo(dateString) {
      const date = typeof dateString === 'number' ? new Date(dateString) : new Date(dateString)
      const now = new Date()
      const diff = now - date
      const days = Math.floor(diff / (1000 * 60 * 60 * 24))
      const months = Math.floor(diff / (1000 * 60 * 60 * 24 * 30))
      const years = Math.floor(diff / (1000 * 60 * 60 * 24 * 365))
      const hours = Math.floor(diff / (1000 * 60 * 60))
      const minutes = Math.floor(diff / (1000 * 60))
      
      if (years > 0) {
        return `${years}年前`
      } else if (months > 0) {
        return `${months}个月前`
      } else if (days > 0) {
        return `${days}天前`
      } else if (hours > 0) {
        return `${hours}小时前`
      } else if (minutes > 0) {
        return `${minutes}分钟前`
      } else {
        return '刚刚'
      }
    }
  }
}
</script>

<style scoped>
.user-profile {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.loading-container, .error-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400px;
}

.profile-header {
  margin-bottom: 30px;
}

.profile-banner {
  position: relative;
  height: 200px;
  overflow: hidden;
  border-radius: 8px;
  margin-bottom: -60px;
}

.banner-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.edit-banner-btn {
  position: absolute;
  bottom: 10px;
  right: 10px;
}

.profile-info {
  position: relative;
  display: flex;
  gap: 30px;
  background: white;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  border: 4px solid white;
}

.edit-avatar-btn {
  position: absolute;
  top: 20px;
  left: 110px;
}

.user-details {
  flex: 1;
}

.username {
  font-size: 28px;
  margin-bottom: 10px;
  color: #333;
}

.user-id {
  font-size: 14px;
  color: #666;
  margin-bottom: 15px;
}

.bio {
  font-size: 16px;
  color: #333;
  margin-bottom: 20px;
  line-height: 1.6;
}

.user-stats {
  display: flex;
  gap: 40px;
  margin-bottom: 20px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-top: 5px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.follow-button, .message-button, .edit-profile-button {
  padding: 8px 24px;
  border-radius: 4px;
  border: none;
  cursor: pointer;
  font-size: 16px;
  transition: all 0.3s;
  text-decoration: none;
  display: inline-block;
  text-align: center;
}

.follow-button {
  background: #ff6b81;
  color: white;
}

.follow-button:hover {
  background: #ff4757;
}

.follow-button.following {
  background: #e0e0e0;
  color: #333;
}

.message-button {
  background: #f0f0f0;
  color: #333;
}

.message-button:hover {
  background: #e0e0e0;
}

.edit-profile-button {
  background: #1890ff;
  color: white;
}

.edit-profile-button:hover {
  background: #40a9ff;
}

.profile-tabs {
  display: flex;
  background: white;
  border-radius: 8px;
  padding: 0 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.tab-item {
  padding: 20px 30px;
  cursor: pointer;
  font-size: 16px;
  position: relative;
  transition: color 0.3s;
}

.tab-item:hover {
  color: #ff6b81;
}

.tab-item.active {
  color: #ff6b81;
  font-weight: 500;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 30px;
  right: 30px;
  height: 3px;
  background: #ff6b81;
}

.profile-content {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.video-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

.video-card {
  cursor: pointer;
  transition: transform 0.3s;
}

.video-card:hover {
  transform: translateY(-5px);
}

.video-cover {
  position: relative;
  padding-top: 56.25%;
  margin-bottom: 10px;
}

.video-cover img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
}

.video-duration {
  position: absolute;
  bottom: 8px;
  right: 8px;
  padding: 2px 6px;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  font-size: 12px;
  border-radius: 4px;
}

.video-title {
  font-size: 16px;
  margin-bottom: 8px;
  line-height: 1.4;
  height: 48px;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.video-stats {
  display: flex;
  gap: 10px;
  font-size: 14px;
  color: #666;
}

.empty-content {
  grid-column: 1 / -1;
  padding: 60px 0;
  text-align: center;
}

.empty-action {
  margin-top: 20px;
}

/* 用户兴趣标签样式 */
.user-interests {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
  margin-bottom: 15px;
}

.interest-label {
  font-size: 16px;
  color: #666;
  margin-right: 5px;
}

.interest-tag {
  background: #f0f0f0;
  color: #333;
  padding: 4px 12px;
  border-radius: 15px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.interest-tag:hover {
  background: #ff6b81;
  color: white;
  transform: translateY(-2px);
}

/* 用户等级样式 */
.user-level {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
  padding: 10px;
  background: #fff9f0;
  border-radius: 8px;
}

.level-badge {
  background: #ff6b81;
  color: white;
  padding: 4px 12px;
  border-radius: 12px;
  font-weight: bold;
}

.level-progress {
  flex: 1;
  height: 8px;
  background: #eee;
  border-radius: 4px;
  overflow: hidden;
}

.level-progress-bar {
  height: 100%;
  background: linear-gradient(90deg, #ff6b81, #ff8797);
  transition: width 0.3s ease;
}

.level-text {
  font-size: 14px;
  color: #666;
  white-space: nowrap;
}

/* 内容筛选样式 */
.content-filters {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}

.filter-select {
  width: 200px;
}

/* 视频卡片增强样式 */
.hot-badge {
  position: absolute;
  top: 8px;
  left: 8px;
  background: #ff4757;
  color: white;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}

.video-stats-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));
  color: white;
  padding: 8px;
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  opacity: 0;
  transition: opacity 0.3s;
}

.video-cover:hover .video-stats-overlay {
  opacity: 1;
}

.overlay-view, .overlay-like {
  display: flex;
  align-items: center;
  gap: 4px;
}

.video-tags {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
  margin-top: 5px;
}

.video-tag {
  font-size: 12px;
  color: #666;
  cursor: pointer;
  transition: color 0.3s;
}

.video-tag:hover {
  color: #ff6b81;
}

.favorite-mark, .like-mark {
  position: absolute;
  top: 8px;
  right: 8px;
  background: rgba(255, 255, 255, 0.8);
  color: #ff6b81;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
}

/* 加载更多样式 */
.load-more {
  text-align: center;
  padding: 20px;
}

/* 兴趣设置页面样式 */
.interests-container {
  padding: 20px;
}

.interests-header {
  margin-bottom: 30px;
}

.interests-header h3 {
  font-size: 20px;
  margin-bottom: 10px;
}

.interests-desc {
  color: #666;
  font-size: 16px;
}

.recommendation-preview {
  margin-top: 40px;
}

.recommendation-preview h4 {
  font-size: 18px;
  margin-bottom: 20px;
}

.small-grid {
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
}

/* 观看历史样式 */
.history-container {
  padding: 20px;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.history-header h3 {
  font-size: 20px;
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.history-item {
  display: flex;
  gap: 15px;
  padding: 15px;
  background: #fafafa;
  border-radius: 8px;
  transition: background 0.3s;
}

.history-item:hover {
  background: #f0f0f0;
}

.history-thumbnail {
  width: 200px;
  height: 112px;
  position: relative;
  cursor: pointer;
  border-radius: 8px;
  overflow: hidden;
  flex-shrink: 0;
}

.history-thumbnail img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.watch-progress {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: rgba(0, 0, 0, 0.3);
}

.progress-bar {
  height: 100%;
  background: #ff6b81;
}

.history-info {
  flex: 1;
  min-width: 0;
}

.history-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 10px;
  cursor: pointer;
  transition: color 0.3s;
}

.history-title:hover {
  color: #ff6b81;
}

.history-meta {
  display: flex;
  gap: 15px;
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
  flex-wrap: wrap;
}

.history-actions {
  display: flex;
  gap: 10px;
}

.action-btn {
  padding: 5px 15px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.action-btn:hover {
  background: #f0f0f0;
  border-color: #ccc;
}

/* 错误页面样式 */
.go-home-btn {
  display: inline-block;
  margin-top: 20px;
  padding: 10px 20px;
  background: #ff6b81;
  color: white;
  text-decoration: none;
  border-radius: 4px;
  transition: background 0.3s;
}

.go-home-btn:hover {
  background: #ff4757;
}

@media (max-width: 768px) {
  .profile-info {
    flex-direction: column;
    align-items: center;
    text-align: center;
  }
  
  .user-stats {
    justify-content: center;
    gap: 20px;
  }
  
  .action-buttons {
    justify-content: center;
    flex-wrap: wrap;
  }
  
  .video-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 480px) {
  .video-grid {
    grid-template-columns: 1fr;
  }
  
  .profile-tabs {
    overflow-x: auto;
    padding: 0;
  }
  
  .tab-item {
    padding: 15px 20px;
  }
}
</style>